﻿#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

struct TreeNode {
    int val;
    TreeNode* left;
    TreeNode* right;
    TreeNode() : val(0), left(NULL), right(NULL) {}
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
    TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
private:
    bool dfs(TreeNode* rootOfA, TreeNode* B) {
        if (B == nullptr) return true;
        else if (rootOfA == nullptr) return false;
        else if (rootOfA->val != B->val) return false;
        else return dfs(rootOfA->left, B->left) && dfs(rootOfA->right, B->right);
    }
public:
    bool isSubStructure(TreeNode* A, TreeNode* B) {
        if (A == nullptr || B == nullptr) return false;
        return dfs(A, B) || isSubStructure(A->left, B) || isSubStructure(A->right, B);
    }
};

Solution solution;

int main() {
    TreeNode* tA = new TreeNode(3, new TreeNode(4, new TreeNode(1), new TreeNode(2)), new TreeNode(5));
    TreeNode* tB = new TreeNode(4, new TreeNode(1), new TreeNode(2));
    cout << solution.isSubStructure(tA, tB) << endl;
    return 0;
}